package com.rtp2p.rtcoresdkdemo.utils;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class RTWiFiUtils {
    private static final String TAG = "RTWiFiUtils";

    public static final int WIFI_NONE = 0; //空密码
    public static final int WIFI_WEP = 1;
    public static final int WIFI_WPA = 2;

    //获取当前手机连接的WiFi名称（ssid）
    public static String getCurrentWiFiSSID(Context context) {
        String ssid = " ";
        if (context == null)return ssid;

        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O_MR1) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager != null){
                NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                if (networkInfo != null) {
                    if (networkInfo.isConnected()) {
                        if (networkInfo.getExtraInfo() != null) {
                            ssid = networkInfo.getExtraInfo();
                        }
                    }
                }
            }
        } else {
            WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            ssid = wifiInfo.getSSID();
            if (TextUtils.isEmpty(ssid) || ssid.contains("unknow ssid")){
                //部分手机拿不到WiFi名称
                int networkId = wifiInfo.getNetworkId();
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
                    if (configuredNetworks != null) {
                        for (WifiConfiguration wifiConfiguration : configuredNetworks) {
                            if (wifiConfiguration.networkId == networkId) {
                                ssid = wifiConfiguration.SSID;
                                break;
                            }
                        }
                    }
                }
            }
        }

        return ssid.replace("\"", "");
    }

    public interface RTScanResults {
        void scanResults(List<ScanResult> scanWifiList);
    }

    /**
     * 获取手机WiFi列表
     * @param async true:异步 false:同步
     * */
    public static void getWifiList(Context context, boolean async, RTScanResults results) {

        WifiManager mWifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (async) {
                    mWifiManager.startScan();
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }


                List<ScanResult> scanWifiList = mWifiManager.getScanResults();
                List<ScanResult> wifiList = new ArrayList<>();
                if (scanWifiList != null && scanWifiList.size() > 0) {
                    HashMap<String, Integer> signalStrength = new HashMap<String, Integer>();
                    for (int i = 0; i < scanWifiList.size(); i++) {
                        ScanResult scanResult = scanWifiList.get(i);
                        //Log.e(TAG, "搜索的wifi-ssid:" + scanResult.SSID+ " frequency="+scanResult.frequency);
                        if (!scanResult.SSID.isEmpty()) {
                            String key = scanResult.SSID + " " + scanResult.capabilities;
                            if (!signalStrength.containsKey(key)) {
                                signalStrength.put(key, i);
                                wifiList.add(scanResult);
                            }
                        }
                    }
                } else {
                    Log.e(TAG, "没有搜索到wifi");
                }

                results.scanResults(wifiList);
            }
        }).start();
    }

    /**
     * 获取手机WiFi列表
     */
    public static void getWifiList(Context context, RTScanResults results) {
        WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        BroadcastReceiver broadcastReceivernew = new BroadcastReceiver() {
            @Override
            public void onReceive(Context ctx, Intent intent) {
                if (intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false)) {
                    results.scanResults(wifiManager.getScanResults());
                } else {
                    results.scanResults(null);
                }
            }
        };

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        context.registerReceiver(broadcastReceivernew, intentFilter);

        context.unregisterReceiver(broadcastReceivernew);
        wifiManager.startScan();
    }

    /**
     * 判断 wifi 是否是 5G 频段.
     * 需要权限:
     * <uses-permission android:name="android.permission.INTERNET" />
     * <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
     * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
     * <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
     */
    public static boolean isWifi24G(Context context, String ssid) {
        Log.d(TAG, "isWifi24G: ssid = " + ssid);
        WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiManager.startScan();
        List<ScanResult> scanResults = wifiManager.getScanResults();
        for (ScanResult scanResult : scanResults) {
            //Log.d(TAG, "isWifi24G: ssid = "+scanResult.SSID + " frequency = " + scanResult.frequency);
            if (ssid.equals(scanResult.SSID)) {
                return scanResult.frequency > 2401 && scanResult.frequency < 2499;
            }
        }
        return false;
    }

    //获取wifi加密方式
    public static int getSecurity(Context context, String ssid) {
        WifiManager mWifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        List<ScanResult> scanResult = mWifiManager.getScanResults();
        for (ScanResult result : scanResult) {
            if (!TextUtils.isEmpty(result.SSID) && ssid.equals(result.SSID)) {
                String capabilities = result.capabilities;
                if (!TextUtils.isEmpty(capabilities)) {
                    if (capabilities.contains("WPA") || capabilities.contains("wpa")) {
                        return WIFI_WPA;
                    } else if (capabilities.contains("WEP") || capabilities.contains("wep")) {
                        return WIFI_WEP;
                    } else {
                        return WIFI_NONE;
                    }
                }
            }
        }
        return -1;
    }

    //是否连接WIFI
    public static boolean isWifiConnected(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            NetworkCapabilities cap = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
            return (cap != null) && cap.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
        } else {
            NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            return (wifiInfo != null) && wifiInfo.isConnected();
        }
    }

    // 检查网络是否可用
    public static boolean networkCheckEnable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo info = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (null == info) {
            return false;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
            return (capabilities != null) && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) && info.isAvailable();
        }
        return false;
    }

    /**
     * 获取当前ip地址
     *
     * @param context
     * @return 手机IP地址
     */
    public static String getLocalIpAddress(Context context) {
        String ip = "";
        try {
            WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int i = wifiInfo.getIpAddress();
            ip= int2ip(i);
        } catch (Exception ex) {
            Log.i(TAG, "getLocalIpAddress: " + " 获取IP出错鸟!!!!请保证是WIFI,或者请重新打开网络!\n" + ex.getMessage());
        }
        return ip;
    }

    /**
     * 将ip的整数形式转换成ip形式
     *
     * @param ipInt
     * @return
     */
    public static String int2ip(int ipInt) {
        return (ipInt & 0xFF) + "." +
                ((ipInt >> 8) & 0xFF) + "." +
                ((ipInt >> 16) & 0xFF) + "." +
                ((ipInt >> 24) & 0xFF);
    }
}
